package com.sxit.tdf.server.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.sxit.tdf.server.entity.User;
import com.sxit.tdf.server.entity.bo.*;
import com.sxit.tdf.server.entity.vo.*;
import com.sxit.tdf.server.exception.TdfException;
import com.sxit.tdf.server.response.R;
import com.sxit.tdf.server.service.IUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.websocket.server.PathParam;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 用户表 前端控制器
 *
 * @author 橙子高🍊
 * @since 2022-02-05
 */
@RestController
@RequestMapping("/user")
@CrossOrigin
@Tag(name = "UserController", description = "用户信息相关接口")
public class UserController {

  @Autowired private IUserService userService;

  @Operation(summary = "通过用户名和密码登录平台")
  @PostMapping("/login")
  public R loginByUsernameAndPassword(@Valid @RequestBody LoginByUserNameAndPasswordFrom from) {

    // 1. 判断是否成功登录
    String userId = userService.loginByUserNameAndPassword(from);
    // 2. 判断是否范围的ID为NULL  如果不为null则登录成功则在Satoken中进行登录
    if (StringUtils.isNotBlank(userId)) {
      StpUtil.login(userId);

      // 3. 获取用户的权限
      Set<String> userPermissions = userService.getUserPermissions(userId);
      String tokenValue = StpUtil.getTokenInfo().getTokenValue();

      return R.ok("登录成功").put("permissions", userPermissions).put("token", tokenValue);
    } else {
      return R.error("登陆失败");
    }
  }

  @Operation(summary = "登出平台")
  @PostMapping("/logout")
  @SaCheckLogin
  public R logout() {

    StpUtil.logout();
    return R.ok("退出成功");
  }

  @Operation(summary = "是否在登录状态")
  @GetMapping("/isLogin")
  public R isLogin() {
    boolean login = StpUtil.isLogin();
    return R.ok().put("isLogin", login);
  }

  @Operation(summary = "获取所有的用户列表")
  @GetMapping("/searchAllUser")
  @SaCheckLogin
  public R searchAllUser() {
    List<UserInfoBo> userInfoBos = userService.searchAllUser();

    return R.ok().put("data", userInfoBos).put("page", 1);
  }

  @Operation(summary = "获取用户信息")
  @PostMapping("/getUserList")
  @SaCheckPermission("USER:SELECT")
  @SaCheckLogin
  public R getUserList(@Valid @RequestBody SiftUserInfoVo siftUserInfoVo) {

    IPage<UserInfoBo> userInfos = userService.getUserInfoBySift(siftUserInfoVo);
    long total = userInfos.getTotal();
    List<UserInfoBo> records = userInfos.getRecords();
    return R.ok().put("data", records).put("total", total);
  }

  @Operation(summary = "获取当前用户的信息")
  @GetMapping("/getCurrentUserInfo")
  @SaCheckLogin
  public R getCurrentUserInfo() {
    // 获取登陆的Id
    String userId = StpUtil.getLoginIdAsString();
    UserInfoBo userInfo = userService.getUserInfo(userId);
    Set<String> userPermissions = userService.getUserPermissions(StpUtil.getLoginIdAsString());
    userInfo.setPermissions(userPermissions);
    return R.ok().put("data", userInfo);
  }

  @Operation(summary = "新增用户")
  @PostMapping("/insertUserInfo")
  @SaCheckPermission("USER:INSERT")
  @SaCheckLogin
  public R insertUserInfo(@Valid @RequestBody InsertUserInfoVo insertUserInfoVo) {

    int i = userService.insertUserInfo(insertUserInfoVo);

    return R.ok();
  }

  @Operation(summary = "通过id获取用户数据")
  @GetMapping("/getUserInfo")
  @SaCheckPermission("USER:SELECT")
  @SaCheckLogin
  public R getUserInfo(@PathParam("id") String id) {
    InsertUserInfoVo insertUserInfoVo = userService.searchUserInfoInInsert(id);
    return R.ok().put("data", insertUserInfoVo);
  }

  @Operation(summary = "更新用户数据")
  @PostMapping("/updateUserInfo")
  @SaCheckPermission("USER:UPDATE")
  @SaCheckLogin
  public R updateUserInfo(@Valid @RequestBody InsertUserInfoVo insertUserInfoVo) {
    System.out.println(insertUserInfoVo);
    int row = userService.updateUserInfo(insertUserInfoVo);
    System.out.println(row);
    if (row == 1) {
      return R.ok("更新成功");
    } else if (row == 0) {
      return R.error("更新失败");
    }
    return R.ok();
  }

  @Operation(summary = "删除用户")
  @PostMapping("/deleteUser")
  @SaCheckLogin
  @SaCheckPermission("USER:DELETE")
  public R deleteUser(@RequestBody DeleteUserBo deleteUserBo) {
    boolean b = userService.removeById(deleteUserBo.getId());

    if (b) {
      return R.ok("删除成功");
    } else {
      return R.ok("删除失败");
    }
  }

  @Operation(summary = "查询某个班级下的学生基本信息")
  @GetMapping("/getClassesIntoUserInfo")
  @SaCheckLogin
  public R getClassesIntoUserInfo(@PathParam("id") int id) {

    List<SimpleClassesIntoUserInfoBo> simpleClassesIntoUserInfoBo =
        userService.getSimpleClassesIntoUserInfoBo(id);
    return R.ok().put("data", simpleClassesIntoUserInfoBo);
  }

  @Operation(summary = "用于用户筛选的信息")
  @GetMapping("/getUserInfoToSift")
  @SaCheckLogin
  public R getUserInfoToSift() {
    List<SimpleUserInfoToSift> simpleUserInfoToSiftList = userService.getSimpleUserInfoToSiftList();
    return R.ok().put("data", simpleUserInfoToSiftList);
  }

  @Operation(summary = "批量修改用户的所属班级")
  @PostMapping("/updateUserClasses")
  @SaCheckLogin
  public R updateUserClasses(@Valid @RequestBody UpdateUserClassVo updateUserClassVo) {

    int classId = updateUserClassVo.getClassId();

    List<User> collect =
        updateUserClassVo.getUserId().stream()
            .map(
                item -> {
                  User user = new User();
                  user.setId(item);
                  user.setClassesId(classId);
                  return user;
                })
            .collect(Collectors.toList());
    System.out.println("----->" + collect);
    boolean update = userService.updateBatchById(collect);
    if (update) {
      return R.ok("添加成功");
    } else {
      return R.error("添加失败");
    }
  }

  @Operation(summary = "讲用户移出班级")
  @PostMapping("removeClasses")
  @SaCheckLogin
  public R removeClasses(@Valid @RequestBody DeleteUserBo deleteUserBo) {

    User user = new User();
    user.setId(deleteUserBo.getId());
    user.setClassesId(0);

    boolean update = userService.updateById(user);
    if (update) {
      return R.ok("删除成功");
    } else {
      return R.ok("删除失败");
    }
  }

  @Operation(summary = "获取教师列表")
  @GetMapping("/getTeacherList")
  @SaCheckLogin
  public R getTeacherList() {
    List<SimpleTeacherList> simpleTeacherList = userService.getSimpleTeacherList();

    return R.ok().put("data", simpleTeacherList);
  }

  @GetMapping("/getSimpleUserInfo")
  @Operation(summary = "获取简易的用户数据")
  @SaCheckLogin
  private R getSimpleUserInfo() {
    List<SimpleUserInfo> list = userService.getSimpleUserInfo();
    return R.ok().put("data", list);
  }

  @PostMapping("updatePrivateUserInfo")
  @Operation(summary = "修改个人用户信息")
  public R updatePrivateUserInfo(
      @Valid @RequestBody UpdatePrivateUserInfoVo updatePrivateUserInfoVo) {

    System.out.println("----" + updatePrivateUserInfoVo);
    User user = new User();
    user.setId(updatePrivateUserInfoVo.getId());

    if (StringUtils.isNotBlank(updatePrivateUserInfoVo.getEmail())) {
      user.setEmail(updatePrivateUserInfoVo.getEmail());
    }
    if (StringUtils.isNotBlank(updatePrivateUserInfoVo.getPhone())) {
      user.setPhone(updatePrivateUserInfoVo.getPhone());
    }

    boolean update = userService.updateById(user);
    if (update) {
      return R.ok("修改成功");
    } else {
      return R.error("修改失败");
    }
  }

  @Operation(summary = "是否能够修改密码")
  @PostMapping("canUpdateUserPassWord")
  public R canUpdateUserPassWord(@Valid @RequestBody UpdateUserPasswordVo updateUserPasswordVo) {
    QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
    System.out.println("---->" + updateUserPasswordVo);
    userQueryWrapper
        .eq("phone", updateUserPasswordVo.getPhone())
        .eq("num", updateUserPasswordVo.getNum())
        .eq("email", updateUserPasswordVo.getEmail());
    User one = userService.getOne(userQueryWrapper);
    System.out.println(one);
    if (one == null) {
      return R.error("信息错误");
    }

    return R.ok("");
  }

  @Operation(summary = "修改密码")
  @PostMapping("modifyPassword")
  public R modifyPassword(@Valid @RequestBody ModifyPasswordVo modifyPasswordVo) {
    QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
    System.out.println("---->" + modifyPasswordVo);
    userQueryWrapper
        .eq("phone", modifyPasswordVo.getPhone())
        .eq("num", modifyPasswordVo.getNum())
        .eq("email", modifyPasswordVo.getEmail());
    User one = userService.getOne(userQueryWrapper);

    if (one == null) {
      throw new TdfException("小贼，你想干什么！！");
    }

    userService.modifyPassword(modifyPasswordVo.getPassword(), one.getId(), one.getUsername());

    return R.ok();
  }

  @Operation(summary = "修改密码")
  @PostMapping("modifyPrivatePassword")
  public R modifyPrivatePassword(@Valid @RequestBody ModifyPrivatePassword modifyPrivatePassword) {

    String loginIdAsString = StpUtil.getLoginIdAsString();
    User byId = userService.getById(loginIdAsString);

    userService.modifyPassword(
        modifyPrivatePassword.getPassword(), byId.getId(), byId.getUsername());
    StpUtil.logout(byId.getId());
    return R.ok();
  }
}
